<template>
  <div class="page-container">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="welcome-card">
          <h2>欢迎使用事件编排管理系统</h2>
          <p>本系统用于管理和运行事件流程，您可以通过左侧菜单进行操作。</p>
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="20" class="stat-row">
      <el-col :span="8">
        <el-card class="stat-card">
          <div class="stat-icon">
            <el-icon><el-icon-document /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-title">事件数量</div>
            <div class="stat-value">{{ events.length }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="stat-card">
          <div class="stat-icon">
            <el-icon><el-icon-folder /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-title">分类数量</div>
            <div class="stat-value">{{ categories.length }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="stat-card">
          <div class="stat-icon">
            <el-icon><el-icon-video-play /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-title">运行次数</div>
            <div class="stat-value">{{ recentRuns }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 最近运行记录 -->
    <el-row :gutter="20" class="recent-row">
      <el-col :span="24">
        <el-card class="recent-card">
          <template #header>
            <div class="card-header">
              <span>最近运行记录</span>
              <el-button class="button" type="primary" text @click="navigateTo('/logs')">查看全部</el-button>
            </div>
          </template>
          <div v-if="recentLogs.length > 0">
            <el-table :data="recentLogs" style="width: 100%">
              <el-table-column prop="eventName" label="事件名称" />
              <el-table-column prop="runTime" label="运行时间">
                <template #default="{ row }">
                  {{ formatDateTime(row.runTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="status" label="运行状态">
                <template #default="{ row }">
                  <el-tag :type="getStatusType(row.status)">
                    {{ getStatusText(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="result" label="运行结果" show-overflow-tooltip />
              <el-table-column label="操作">
                <template #default="{ row }">
                  <el-button type="primary" size="small" @click="viewLogDetail(row.id)">详情</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-empty v-else description="暂无运行记录" />
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" class="recent-row">
      <el-col :span="12">
        <el-card class="recent-card">
          <template #header>
            <div class="card-header">
              <span>最近事件</span>
              <el-button class="button" type="primary" text @click="navigateTo('/events')">查看全部</el-button>
            </div>
          </template>
          <div v-if="events.length > 0">
            <el-table :data="events.slice(0, 5)" style="width: 100%">
              <el-table-column prop="name" label="事件名称" />
              <el-table-column prop="category" label="分类" />
              <el-table-column prop="createTime" label="创建时间" />
              <el-table-column label="操作">
                <template #default="{ row }">
                  <el-button type="primary" size="small" @click="navigateTo(`/events/${row.id}`)">详情</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-empty v-else description="暂无事件" />
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="recent-card">
          <template #header>
            <div class="card-header">
              <span>最近分类</span>
              <el-button class="button" type="primary" text @click="navigateTo('/categories')">查看全部</el-button>
            </div>
          </template>
          <div v-if="categories.length > 0">
            <el-table :data="categories.slice(0, 5)" style="width: 100%">
              <el-table-column prop="name" label="分类名称" />
              <el-table-column prop="eventCount" label="事件数量" />
              <el-table-column prop="createTime" label="创建时间" />
              <el-table-column label="操作">
                <template #default="{ row }">
                  <el-button type="primary" size="small" @click="navigateTo(`/categories/${row.id}`)">查看</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-empty v-else description="暂无分类" />
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 日志详情弹窗 -->
    <el-dialog
      v-model="logDetailDialogVisible"
      title="日志详情"
      width="800px"
    >
      <div v-if="currentLogDetail">
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="日志ID">{{ currentLogDetail.id }}</el-descriptions-item>
          <el-descriptions-item label="事件名称">{{ currentLogDetail.eventName }}</el-descriptions-item>
          <el-descriptions-item label="运行时间">{{ formatDateTime(currentLogDetail.runTime) }}</el-descriptions-item>
          <el-descriptions-item label="运行时长">{{ formatDuration(currentLogDetail.duration) }}</el-descriptions-item>
          <el-descriptions-item label="运行状态">
            <el-tag :type="getStatusType(currentLogDetail.status)">{{ getStatusText(currentLogDetail.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="运行结果">{{ currentLogDetail.result }}</el-descriptions-item>
        </el-descriptions>
        
        <h4 class="detail-subtitle">日志内容</h4>
        <div class="log-container">
          <div v-if="currentLogDetail.logs && currentLogDetail.logs.length > 0">
            <div 
              v-for="(log, index) in currentLogDetail.logs" 
              :key="index"
              :class="['log-item', log.type]"
            >
              {{ formatDateTime(log.timestamp) }} - {{ log.message }}
            </div>
          </div>
          <div v-else class="empty-log">
            <p>无日志内容</p>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="logDetailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { Document as ElIconDocument, Folder as ElIconFolder, VideoPlay as ElIconVideoPlay } from '@element-plus/icons-vue'
import { ElMessageBox } from 'element-plus'

const store = useStore()
const router = useRouter()

const logDetailDialogVisible = ref(false)
const currentLogDetail = ref(null)

const events = computed(() => {
  return store.state.events.map(event => {
    const category = store.getters.getCategoryById(event.categoryId)
    return {
      ...event,
      category: category ? category.name : '未分类'
    }
  })
})

const categories = computed(() => {
  return store.state.categories.map(category => {
    const eventCount = store.getters.getEventsByCategory(category.id).length
    return {
      ...category,
      eventCount
    }
  })
})

const recentRuns = computed(() => {
  // 从store中获取日志总数
  return store.state.totalLogs ? `${store.state.totalLogs} 次` : '0 次'
})

const recentLogs = computed(() => {
  return store.state.eventLogs || []
})

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString()
}

// 格式化运行时长
const formatDuration = (ms) => {
  if (!ms) return '0秒'
  if (ms < 1000) return `${ms}毫秒`
  
  const seconds = Math.floor(ms / 1000)
  if (seconds < 60) return `${seconds}秒`
  
  const minutes = Math.floor(seconds / 60)
  const remainSeconds = seconds % 60
  return `${minutes}分${remainSeconds}秒`
}

// 获取状态显示类型
const getStatusType = (status) => {
  switch (status) {
    case 'success': return 'success'
    case 'failed': return 'warning'
    case 'error': return 'danger'
    default: return 'info'
  }
}

// 获取状态显示文本
const getStatusText = (status) => {
  switch (status) {
    case 'success': return '成功'
    case 'failed': return '失败'
    case 'error': return '错误'
    default: return status
  }
}

// 查看日志详情
const viewLogDetail = async (logId) => {
  try {
    currentLogDetail.value = await store.dispatch('getLogDetail', logId)
    logDetailDialogVisible.value = true
  } catch (error) {
    ElMessageBox.alert('获取日志详情失败', '错误', { type: 'error' })
  }
}

const navigateTo = (path) => {
  router.push(path)
}

onMounted(() => {
  store.dispatch('fetchEvents')
  store.dispatch('fetchCategories')
  // 获取日志数据，显示最近5条记录
  store.dispatch('fetchAllEventLogs', { page: 1, limit: 5 })
})
</script>

<style scoped>
.welcome-card {
  margin-bottom: 20px;
}

.stat-row {
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  flex-direction: row;
  padding: 15px;
}

.stat-icon {
  font-size: 40px;
  margin-right: 15px;
  color: #409eff;
}

.stat-info {
  display: flex;
  flex-direction: column;
}

.stat-title {
  font-size: 16px;
  color: #909399;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-top: 5px;
}

.recent-row {
  margin-bottom: 20px;
}

.recent-card {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-subtitle {
  margin: 20px 0 10px;
  font-size: 16px;
  color: #606266;
}

.log-container {
  height: 300px;
  overflow-y: auto;
  background-color: #303133;
  color: #fff;
  font-family: monospace;
  padding: 10px;
  border-radius: 4px;
}

.empty-log {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #909399;
}

.log-item {
  line-height: 1.5;
  margin-bottom: 5px;
}

.log-item.success {
  color: #67c23a;
}

.log-item.error {
  color: #f56c6c;
}

.log-item.info {
  color: #e6e6e6;
}

.log-item.warning {
  color: #e6a23c;
}
</style> 